/*
 * @Author: january.cjy
 * @Date: 2021-11-01 16:15:18
 * @Last Modified by: january.cjy
 * @Last Modified time: 2022-04-11 17:26:38
 */
#pragma once

#include "../../../mysql_config.def"

#include <OUT.h>
#include <iostream>
#include <llvm/Support/raw_ostream.h>
#include <mysql.h>
#include <string>

#ifndef CONNECTION_ON_
#define CONNECTION_ON_ 1

namespace cmg {

using namespace std;

class Connection {
public:
  /// 自己指定连接的数据库配置
  Connection(string ModuleName, const char *host, const char *user,
             const char *passwd, const char *db, unsigned int port,
             const char *unix_socket, unsigned long clientflag)
      : ModuleName(ModuleName) {
    mysql_init(&conn);
    mysql_real_connect(&conn, host, user, passwd, db, port, unix_socket,
                       clientflag);
  }

  /// 使用默认的数据库配置: january.plus本地环境上的配置
  Connection(string ModuleName) : ModuleName(ModuleName) {
    mysql_init(&conn);
    if (mysql_real_connect(&conn, HOST, USER, PASSWORD, DATABASE, 0, NULL,
                           CLIENT_FOUND_ROWS)) {
      ERRS_.changeColor(llvm::raw_ostream::YELLOW);
      ERRS_ << "Connect to mysql: " << ModuleName << "\n";
      ERRS_.resetColor();
    } else {
      ERRS_.changeColor(llvm::raw_ostream::RED);
      ERRS_ << "Fail to connect to mysql: " << ModuleName << "\n";
      ERRS_.resetColor();
    }
  }

  bool connect();
  bool insertToVtables(string &module, string &vtable,
                       unsigned int offset_to_top, string &virtual_function);
  bool insertToTypeMetadata(string &type_metadata, string &vtable,
                            unsigned int offset);
  bool insertToVitualCall(string &module, string &user_symbol,
                          string &type_metadata, unsigned int offset);
  bool insertToSymbolDefinition(string &module, string &symbol,
                                unsigned int symbol_tag,
                                string linkage = "null",
                                string visibility = "null");
  bool insertToSymbolUse(string &module, string &user_symbol,
                         string &used_symbol);

private:
  MYSQL conn;
  string ModuleName;
};
} // namespace cmg

#endif